<template>
  <div class="container">
    <uv-navbar :placeholder="true">
      <template v-slot:left>
        <view class="uv-nav-slot flex alignCenter" @click="proxy.$utils.back()">
          <uv-icon name="arrow-left" size="19"></uv-icon>
          <uv-avatar :src="info.logo" size="28"></uv-avatar>
          <view class="nickName fz16 bold">{{info.nickName}}</view>
          <!-- <view class="matching">
            匹配度 {{info.matchingDegree}}%
          </view> -->
        </view>
      </template>

      <template v-slot:right>
        <view :style="iconStyle()" class="flex alignCenter">
          <view class="uv-nav-slot" @click="toFollow">
            <view class="isFollow fz12">{{isFollow ? '取消关注' : '关注'}}</view>
          </view>
          <uv-icon name="more-dot-fill" size="19"></uv-icon>
        </view>
      </template>
    </uv-navbar>

    <view class="top" v-if="false">
      <view class="label fz14">{{info.sex==1?'他':'她'}}希望的你</view>
      <view class="tags flex alignCenter" v-if="info.hisTags">
        <view class="tag fz12" v-for="(tag, index) in info.hisTags.split(',')" :key="index">{{tag}}</view>
      </view>

      <view class="label fz14">{{info.sex==1?'他':'她'}}是这样的</view>
      <view class="tags flex alignCenter" v-if="info.oneselfTags">
        <view class="tag pink fz12" v-for="(tag, index) in info.oneselfTags.split(',')" :key="index">{{tag}}</view>
      </view>
    </view>

    <scroll-view id="chatWrap" @scroll="scroll" :scroll-top="scrollTop" @scrolltoupper="scrolltoupper" :scroll-y="true" :style="{height:chatHeight+'px'}">
      <view class="chat-list" id="chatList">
        <view class="chat-item" v-for="(item, index) in historyMsgs" :key="index">
          <view class="left flex" :class="{alignCenter:item.type=='audio'}" v-if="item.to!=info.userId">
            <uv-avatar :src="info.logo" @click="toUser('other')"></uv-avatar>
            <view class="con">
              <view class="text fz16" v-if="item.type=='text'">{{item.body.text}}</view>
              <view class="geo fz16" v-else-if="item.type=='location'" @click="toLocation(item.body)">
                <view class="title">{{item.body.address}}</view>
                <view class="address">
                  <image :src="mapImageUrl(item.body.latitude, item.body.longitude)" mode="widthFix" />
                </view>
              </view>
              <view class="geo" v-else-if="item.type=='image'">
                <view class="address" @click="proxy.$auth.previewImage([item.body.originalUrl],0)">
                  <image :src="item.body.originalUrl" mode="widthFix" />
                </view>
              </view>
              <view v-else-if="item.type=='audio'">
                <customAudio :audioSrc="item.body.audioUrl" :time="item.body.duration"></customAudio>
              </view>
              <view v-else-if="item.type=='custom'" class="flex alignCenter customMsg">
                <view class="image">
                  <image :src="item.attach.url" mode="widthFix" />
                </view>
                <view>{{item.attach.name}} x{{item.attach.num}}</view>
              </view>
            </view>
          </view>
          <view class="right flex justifyEnd" :class="{alignCenter:item.type=='audio'}" v-else>
            <view class="con">
              <view class="text fz16" v-if="item.type=='text'">{{item.body.text}}</view>
              <view class="geo fz16" v-else-if="item.type=='location'" @click="toLocation(item.body)">
                <view class="title">{{item.body.address}}</view>
                <view class="address">
                  <image :src="mapImageUrl(item.body.latitude, item.body.longitude)" mode="widthFix" />
                </view>
              </view>
              <view class="geo" v-else-if="item.type=='image'">
                <view class="address" @click="proxy.$auth.previewImage([item.body.originalUrl],0)">
                  <image :src="item.body.originalUrl" mode="widthFix" />
                </view>
              </view>
              <view v-else-if="item.type=='audio'">
                <customAudio :audioSrc="item.body.audioUrl" :time="item.body.duration"></customAudio>
              </view>
              <view v-else-if="item.type=='custom'" class="flex alignCenter customMsg">
                <view class="image">
                  <image :src="item.attach.url" mode="widthFix" />
                </view>
                <view>{{item.attach.name}} x{{item.attach.num}}</view>
              </view>
            </view>
            <uv-avatar :src="userInfo.logo" @click="toUser('own')"></uv-avatar>
          </view>
        </view>
      </view>
    </scroll-view>

    <view id="chatActionDiv">
      <chatAction @sendAddressMsg="sendAddressMsg" @sendAudioMsg="sendAudioMsg" @getChatActionHeight="setCss" @sendMessage="sendMsg" @sendImageMsg="sendImageMsg"></chatAction>
    </view>
  </div>
</template>

<script setup lang="ts">
import customAudio from "@/components/uv/customAudio.vue";
import chatAction from "@/packagePages/chatIm/components/chatAction.vue";
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();
const instance = getCurrentInstance();

let props = defineProps(["userId"]);

//im
import YeIMStore from "@/stores/YeIM";
const YeIM = YeIMStore();

let userId;
let info = ref({}); //用户信息
let isFollow = ref(false); //是否关注
let scrollTop = ref(0); //滚动条位置
let chatHeight = ref(0); //聊天区域高度
let historyMsgs = ref([]); //历史消息
let loading = ref(false);
let nextMessageId; //下一次续拉的消息ID
let isScrollBottom = true; //是否滚动到底部
let footerHeight; //底部高度
let isScrolltoupper = false; //是否允许上拉加载

let userInfo = computed(() => {
  let slParams = uni.getStorageSync("slParams");
  return slParams.userInfo;
});

function iconStyle() {
  let right = 0;
  // #ifdef MP-WEIXIN
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
  right = menuButtonInfo.width;
  // #endif
  return {
    paddingRight: `${right}px`,
  };
}

async function init() {
  await getUserInfo();
  setCss();
  getHistoryMsgs();
}

function scroll(event) {
  let { detail } = event;
  //console.log("detail", detail);
}

let getUserInfo = async () => {
  //用户信息
  info.value = await counter.getUserInfo(userId);
  console.log("用户信息", info.value);

  //关注状态
  isFollow.value = await proxy.$apis.attentionToIt({ friendId: userId });
  console.log("关注状态", isFollow.value);
};

function toUser(type) {
  proxy.$utils.toLink(
    `/packagePages/user/details?id=${
      type == "other" ? userId : counter.slParams.userInfo.userId
    }`
  );
}

function setCss(hei?) {
  nextTick(async () => {
    if (hei) {
      footerHeight = hei;
    } else {
      let bottomHeight = await viewInfo("#chatActionDiv", "height");
      if (bottomHeight) footerHeight = bottomHeight;
    }
    let top = await viewInfo("#chatWrap", "top");
    const systemInfo = uni.getSystemInfoSync();
    chatHeight.value =
      systemInfo.windowHeight - Number(footerHeight) - Number(top);
    scrollToBottom();
  });
}

//滚动到页面底部
function scrollToBottom() {
  YeIM.clearConversationUnread(userId);
  nextTick(async () => {
    let chatWrapHeight = await viewInfo("#chatWrap", "height");
    let chatListHeight = await viewInfo("#chatList", "height");
    if (chatListHeight > chatWrapHeight)
      scrollTop.value = Number(chatListHeight) - Number(chatWrapHeight);
  });
}

function close() {
  userId = null;
  nextMessageId = null;
  isScrollBottom = true;
}

async function getHistoryMsgs() {
  let { data } = await YeIM.getHistoryMessageList(userId, nextMessageId);
  let arr = proxy.$utils.deepcopy(historyMsgs.value);
  if (data.list.length) {
    arr = proxy.$utils.filterArr(arr, data.list, "messageId");
  }
  historyMsgs.value = arr.sort(proxy.$utils.compare("time"));
  nextMessageId = data.nextMessageId;
  if (isScrollBottom) scrollToBottom();
  isScrollBottom = false;
}

async function toFollow() {
  try {
    loading.value = true;
    //已关注
    if (isFollow.value) {
      await proxy.$apis.userUnFocus({ friendId: userId });
      proxy.$utils.showToast("已取消关注");
    } else {
      await proxy.$apis.contacts({ friendId: userId });
      proxy.$utils.showToast("已成功关注");
    }
    getUserInfo();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

//滚动到顶部
function scrolltoupper() {
  if (!isScrolltoupper) return;
  isScrollBottom = false;
  getHistoryMsgs();
}

//发送文本消息
async function sendMsg(text) {
  let { data } = await YeIM.sendMessage(info.value.userId, { text }, "text");
  historyMsgs.value.push(data);
  scrollToBottom();
}

function toLocation(params) {
  proxy.$auth.openLocation({
    latitude: params.latitude,
    longitude: params.longitude,
    name: params.address,
  });
}

//发送图片
async function sendImageMsg(text) {
  let resp = await proxy.$auth.getImageInfo(text);
  let body = {
    file: {
      tempFilePath: text, //本地图片临时路径
      width: resp.width, //图片宽度
      height: resp.height, //图片高度
    },
  };
  let { data } = await YeIM.sendMessage(info.value.userId, body, "image");
  historyMsgs.value.push(data);
  scrollToBottom();
}

//发送语音消息
async function sendAudioMsg(text) {
  let body = {
    audioUrl: await counter.uploadFile(text), //音频网络Url
    duration: await proxy.$utils.countAudioTime(text), //音频时长，单位：秒
  };
  let { data } = await YeIM.sendMessage(info.value.userId, body, "audio");
  historyMsgs.value.push(data);
  scrollToBottom();
}

//发送地址
async function sendAddressMsg(obj) {
  let body = {
    address: obj.name, //地址名称
    description: obj.address, //地址详细描述
    longitude: obj.longitude, //经度
    latitude: obj.latitude, //纬度
  };
  let { data } = await YeIM.sendMessage(info.value.userId, body, "location");
  historyMsgs.value.push(data);
  scrollToBottom();
}

function mapImageUrl(lat, lng) {
  return proxy.$atlas.staticmapImage(lat, lng);
}

//页面加载完成后初始化
function loadData(e) {
  isScrolltoupper = false;
  userId = e;
  isScrollBottom = true;
  init();
  setTimeout(() => {
    isScrolltoupper = true;
  }, 4000);
}

//获取页面元素信息
function viewInfo(id, type) {
  return new Promise((resolve, reject) => {
    uni
      .createSelectorQuery()
      .in(instance)
      .select(id)
      .boundingClientRect((data) => {
        if (data) {
          resolve(data[type]);
        } else {
          resolve(0);
        }
      })
      .exec();
  });
}

watch(
  () => YeIM.news,
  (newValue, oldValue) => {
    if (newValue && newValue.from == userId) {
      historyMsgs.value.push(newValue);
      scrollToBottom();
    }
  },
  { deep: true, immediate: true }
);

defineExpose({ close, loadData });
</script>



<style lang="scss" scoped>
.container {
  .nickName {
    color: #333333;
    padding: 0 10px;
  }
  .matching {
    background: linear-gradient(to right, #ffa0d2, #4439ff);
    border-radius: 11px;
    color: #fff;
    font-size: 12px;
    padding: 3px 6px;
  }
  .isFollow {
    background: #f2628d;
    border-radius: 15px;
    line-height: 21px;
    color: white;
    padding: 3px 12px;
    margin-right: 12px;
  }
  .top {
    padding: 10px 27px;
    box-shadow: 0 2px 4px 0px rgba(0, 0, 0, 0.05);
    border-radius: 0 0 15px 15px;
    .label {
      color: #999999;
    }
    .tags {
      color: #9e06ff;
      flex-wrap: wrap;
      margin-top: 5px;
      .tag {
        padding: 4px 6px;
        margin-right: 10px;
        margin-bottom: 10px;
        border: 1px solid #9e06ff;
        border-radius: 12px;
      }
      .pink {
        border-color: #f667a7 !important;
        color: #f667a7 !important;
      }
    }
  }
  .chat-list {
    padding: 15px;
    .chat-item {
      margin-bottom: 10px;
      .left {
        .con {
          margin-left: 10px;
        }
        .text {
          padding: 9px 10px 9px 10px;
          border-radius: 20px 20px 20px 0;
          background: #ededed;
          color: #333333;
        }
      }
      .right {
        .con {
          margin-right: 10px;
        }
        .text {
          color: #353943;
          padding: 9px 10px 9px 10px;
          border-radius: 20px 20px 0px 20px;
          background: #e5f4ff;
        }
      }
      .geo {
        width: 150px;
        background-color: white;
        border-radius: 5px;
        .title {
          padding: 10px;
          font-size: 14px;
        }
        .address {
          image {
            display: block;
          }
        }
      }
      .customMsg {
        background-color: white;
        padding: 3px 10px;
        border-radius: 5px;
        font-size: 14px;
        .image {
          width: 30px;
          margin-right: 2px;
        }
      }
    }
  }
}
</style>
